var planId = getQueryString("id");
var deptZtree;
$(function () {
    $("#jqGrid").Grid({
        url: '../devmainbaseam/listAll',
        rownumWidth: 40,
        sortname: 'CREATE_DATE',
        sortorder: 'DESC',
        colModel: [
            {label: '选项编码', name: 'code', index: 'CODE', width: 70},
            {label: '选项名称', name: 'name', index: 'NAME', width: 60},
            {label: '设备类型', name: 'devTypeName', index: 'DEV_TYPE_NAME', width: 100},
            {label: '供应厂家', name: 'devSupplyName', index: 'DEV_SUPPLY', width: 100},
            {label: '维护内容', name: 'checkContent', index: 'CHECK_CONTENT'},
            {label: '维护标准', name: 'checkSt', index: 'CHECK_ST'},
            {label: '物料需求', name: 'materialRequ', index: 'MATERIAL_REQU', width: 60,
                formatter: function (value) {
                    return value?value:'\\';
                }
            },
            {label: '方法手段', name: 'methodType', index: 'METHOD_TYPE'},
            {label: '生产', name: 'checkDatePrud', index: 'CHECK_DATE_PRUD', width: 50},
            {label: '非生产', name: 'checkDateUprud', index: 'CHECK_DATE_UPRUD', width: 50},
            {
                label: '实施频率', name: 'freRate', index: 'FRE_RATE', width: 60,
                formatter: function (value) {
                    return sysEnums.FRERATE[value];
                }
            },
            {label: '人次', name: 'perEv', index: 'PER_EV', width: 60},
            {
                label: '失效标识', name: 'lockFlag', index: 'LOCK_FLAG', width: 60,
                formatter: function (value) {
                    return sysEnums.SWITCH_FLAG[value];
                }
            },
            {
                label: '履历', width: 60, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' onclick='vm.goHistory(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {label: 'devType', name: 'devType', index: 'DEV_TYPE',  hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}]
    });
    vm.getSelectTreeShow();
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        beforeCheck: true,
    }

};

//类型树-首页加载增加查询方法
var typeSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    vm.q.devType = treeObj.typeCode;
    vm.query();
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        devMainBase: {
            devTypeName:"",
            devType:"",
            planId:"",
            devSupply:"", // 供应厂商编码
            devSupplyName:'', // 供应厂商名称
            freRate:"",
            checkType:1,
            mainType:1
        },
        ruleValidate: {
            name: [
                {required: true, message: '选项名称不能为空', trigger: 'change'}
            ],
            devSupply: [
                {required: true, message: '供应厂家不能为空', trigger: 'change'}
            ],
            freRate: [
                {required: true, type: 'number', message: '实施频次不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: '',
            code:'',
            devType:'',
            devSupplyName:'', // 设备供应厂商名称
            mainType:'',
            freRate:''
        },
        freRateArray: enumsToList("FRERATE2"),
        //预测性维护-设备状态
        devStatusList:enumsToList("MAINTAIN_BASE_DEV_STATUS"),
        //属性
        attributeList:enumsToList("MAINTAIN_BASE_ATTRIBUTE"),
    },
    methods: {
        goHistory: function(id){
            // 跳转到设备维护履历
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-bars"></i> 变动履历',
                content: '../device/devmainbasehistory.html?devMainBaseId=' + id
            })
        },
        loadFacType:function(){
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择厂家',
                content: '../sys/factorytype_choose.html?type=0',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.devMainBase.devSupply = res.faCode;
                        vm.devMainBase.devSupplyName = res.faName;
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.devMainBase = {
                mainType:'',
                attribute:'',
                name:'',
                devStatus: '',
                freRate:'',
                perEv:'',
                devSupply:'',
                devSupplyName:'',
                devType:'',
                devTypeName:'',
                checkDatePrud:'',
                checkDateUprud:'',
                checkTool:'',
                methodType:'',
                checkSt:'',
                remark:'',
                id: ''
            };
            vm.getTreeShow();
        },
        update: function (event) {
            var  id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
            vm.getTreeShow();
        },
        saveOrUpdate: function (event) {
            var url = vm.devMainBase.id ? '../devmainbaseam/update':'../devmainbaseam/save';
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.devMainBase),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devmainbaseam/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devmainbaseam/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.devMainBase = r.devMainBase;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                search: true,
                postData: {'name': vm.q.name,'code':vm.q.code,'devType':vm.q.devType,'devSupplyName':vm.q.devSupplyName,'freRate':vm.q.freRate,'mainType':vm.q.mainType},
                page: page
            }).trigger("reloadGrid", [{ page: 1}]);

            // 取消选中
            deptZtree.cancelSelectedNode();
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                code:'',
                devType:'',
                devSupplyName:'', // 供应厂商名称
                mainType:'',
                freRate:''
            };
            // 取消选中
            deptZtree.cancelSelectedNode();
            deptZtree.expandAll(false);
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    var node = ztree.getNodeByParam("typeCode", vm.devMainBase.devTypeName);
                    if (node) {
                        ztree.selectNode(node);
                        if(node.devTypeName){
                            vm.devMainBase.devTypeName = node.devTypeName;
                        }else{
                            vm.devMainBase.devTypeName = '无';
                        }

                    } else {
                        node = ztree.getNodeByParam("id", "0");
                        ztree.selectNode(node);
                    }
                }
            });
        },
        getSelectTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    deptZtree = $.fn.zTree.init($("#devTypeTree"), typeSetting, r.list);
                }
            });
        },
        devTypeShow: function () {
            openWindow({
                title: "选择设备类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    if (nodes && nodes.length > 0) {
                        var current = nodes[0];
                        if (current.level == 2) {
                            vm.devMainBase.devType = current.typeCode;
                            vm.devMainBase.devTypeName = current.typeName;
                            layer.close(index);
                        } else {
                            alert('请选择设备设备小类！');
                        }
                    } else {
                        alert('请选择一条记录！');
                    }
                }
                /*btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    vm.devMainBase.devType = node[0].typeCode;
                    vm.devMainBase.devTypeName = node[0].typeName;
                    layer.close(index);
                }*/
            });
        },
        switchFlag: function (status) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            var rows = getSelectedRowDatas("#jqGrid");
            var flag = 0;
            for (var j = 0; j<rows.length; j++){
                if (rows[j].approvalStatus === '已审核') {
                    flag++;
                }
            }

            // 启用
            if (status === 'on') {
                confirm('确定要启用？', function () {
                    Ajax.request({
                        url: "../devmainbaseam/switchOn" ,
                        params: JSON.stringify(ids),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                });
            }

            // 禁用
            if (status === 'off') {
                confirm('确定要禁用？', function () {
                    Ajax.request({
                        url: "../devmainbaseam/switchOff" ,
                        params: JSON.stringify(ids),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                });
            }
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles()
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.err
                })
            }
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        //数据导出
        exportData: function () {
            window.open('../devmainbaseam/export');
        },
    }
});
